package com.hrt.datasender.datasent.serial;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.btcode.common.PropertiesUnit;
import com.btcode.exception.MsgException;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

public final class SerialManager {

    public OutputStream out;
    public InputStream in;
    private final int comWaitTime = 2000;

    private static volatile SerialManager instance = null;

    private SerialManager() throws Exception {

        String port = PropertiesUnit.getValue("SerialSender", "port");

        CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(port);   
        SerialPort sPort = (SerialPort) portId.open(port, comWaitTime);

        int baudRate = PropertiesUnit.getInt("SerialSender", "baudRate");
        int dataBit = PropertiesUnit.getInt("SerialSender", "dataBit");
        int stopBit = PropertiesUnit.getInt("SerialSender", "stopBit");
        int parity = PropertiesUnit.getInt("SerialSender", "parity");

        sPort.setSerialPortParams(baudRate, dataBit, stopBit, parity);

        in = new BufferedInputStream(sPort.getInputStream());
        out = sPort.getOutputStream();

        System.out.println("初始串口化成功");
    }

    public static SerialManager getInstance() {

        if (instance == null) {
            synchronized (SerialManager.class) {
                if (instance == null) {
                    try {
                        instance = new SerialManager();
                    } 
                    catch (Exception e) {
                        throw new MsgException("", e);
                    }

                }
            }
        }
        return instance;
    }

}
